package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReentrantReadWriteLock 写锁的降级
 */
public class _07_ReentrantReadWriteLock_CachedData {

    public static class CachedData {
        Object data;
        volatile boolean cacheValid;
        final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

        void processCachedData() {
            rwl.readLock().lock();
            if (!cacheValid) {
                // 获取写锁之前必须释放读锁（不允许升级锁），否则会阻塞住
                rwl.readLock().unlock();
                rwl.writeLock().lock();
                try {
                    // 重新检测cacheValid状态，因为可能有其他线程改掉了该状态
                    if (!cacheValid) {
                        data = getData(); // 缓存数据
                        cacheValid = true;
                    }
                    // 释放写锁前降级获取读锁
                    rwl.readLock().lock();
                } finally {
                    rwl.writeLock().unlock(); // 释放写锁，扔持有读锁
                }
            }

            try {
                use(data); // 使用数据
            } finally {
                rwl.readLock().unlock(); // 释放读锁
            }
        }

        Object getData() {
            return new Object();
        }

        void use(Object data) {
            // use data
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CachedData cachedData = new CachedData();
        cachedData.processCachedData();
    }

}
